import { javascriptGenerator } from 'blockly/javascript';
import { CustomFunction } from '../../services/custom-function.service';

// 
const registeredCustomGenerators = new Set<string>();

export function registerCustomFunctionGenerator(customFunction: CustomFunction) {
  const blockName = `custom_function_${customFunction.name}`;
  
  // 
  if (registeredCustomGenerators.has(blockName)) {
    console.log(`Generator for ${blockName} already registered, skipping registration`);
    return;
  }
  
  javascriptGenerator.forBlock[blockName] = function(block) {
    // 
    const paramValues = customFunction.params.map((_, index) => {
      return javascriptGenerator.valueToCode(block, `PARAM_${index}`, 0) || 'undefined';
    });
    
    // 
    const code = `${customFunction.name}(${paramValues.join(', ')})`;
    
    // 
    if (customFunction.hasReturnValue) {
      return [code, 0]; // 0 
    } else {
      return code + ';\n';
    }
  };
  
  // 
  registeredCustomGenerators.add(blockName);
  console.log(`Generator for ${blockName} registered successfully`);
}

export function registerCustomFunctionGenerators(customFunctions: CustomFunction[]) {
  customFunctions.forEach(func => registerCustomFunctionGenerator(func));
}